<template>
  <view class="pc-page-bg">
    <RemindWebSocket />
    <view v-if="isLoading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">正在加载个人信息...</text>
    </view>

    <view v-else class="main-content">
      <!-- 头部标题 -->
      <view class="main-header">
        <el-icon class="back-btn" @click="onCancel"><ArrowLeft /></el-icon>
        <text class="page-title">个人信息填写</text>
      </view>
      <view class="main-container">
        <view class="left-nav">
          <view class="custom-nav-list">
            <view 
              v-for="(item, index) in navItems" 
              :key="index"
              :class="['custom-nav-item', { 'active': currentTab === index }]"
              @click="switchTab(index)"
            >
              {{ item.title }}
            </view>
          </view>
        </view>

        <view class="form-content">
        <view class="form-section" id="section-basic">
          <view class="section-title">基本信息</view>
          <view class="form-grid">
            <view class="form-item" style="grid-column: span 2;">
              <text class="form-label required">姓名</text>
              <el-input v-model="form.name" @focus="setCurrentTab(0)" placeholder="请输入姓名" />
            </view>

            <view class="form-item one-sixth">
              <text class="form-label required">性别</text>
              <el-select v-model="form.gender" @focus="setCurrentTab(0)" placeholder="请选择">
                <el-option 
                  v-for="item in dictData.gender" 
                  :key="item.dictCode" 
                  :label="item.dictLabel" 
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </view>

            <view class="form-item one-sixth native-place">
              <text class="form-label required">籍贯</text>
              <el-cascader
                v-model="form.nativePlace"
                :options="provinceAndCityData"
                placeholder="请选择省/市"
                @focus="setCurrentTab(0)"
                style="width: 100%"
                clearable
                :props="{
                  value: 'label',
                  label: 'label',
                  children: 'children'
                }"
              />
            </view>

            <view class="form-item avatar-item">
              <text class="form-label">本人头像</text>
              <view class="avatar-upload">
                <view class="avatar-container">
                  <image v-if="getAvatarSrc(form.avatar)" :src="getAvatarSrc(form.avatar)" class="avatar-img"></image>
                  <view v-else class="default-avatar-placeholder">
                    <uni-icons type="person" size="40" color="#c0c4cc" />
                  </view>
                </view>
                <view class="upload-btn-container">
                  <button class="upload-btn" @click="chooseAvatar">上传头像</button>
                </view>
              </view>
            </view>

            <view class="form-item one-sixth age">
              <text class="form-label required">年龄</text>
              <el-input v-model="form.age" @focus="setCurrentTab(0)" type="number" placeholder="年龄" disabled />
            </view>

            <view class="form-item one-sixth birth-date">
              <text class="form-label required">出生日期</text>
              <el-date-picker
                v-model="form.birthDate"
                type="date"
                placeholder="请选择出生日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                @focus="setCurrentTab(0)"
                style="width: 100%"
              />
            </view>

            <view class="form-item education" style="grid-column: span 2;">
              <text class="form-label required">文化程度</text>
              <el-select v-model="form.education" @focus="setCurrentTab(0)" placeholder="请选择">
                <el-option label="小学及以下" value="小学及以下"></el-option>
                <el-option label="初中" value="初中"></el-option>
                <el-option label="高中" value="高中"></el-option>
                <el-option label="大学" value="大学"></el-option>
                <el-option label="研究生及以上" value="研究生及以上"></el-option>
              </el-select>
            </view>
          </view>
        </view>

        <view class="form-section" id="section-family">
          <view class="section-title">家庭关系</view>
          <view class="form-grid">
            <view class="form-item half-width">
              <text class="form-label required">居住地址</text>
              <el-input v-model="form.address" @focus="setCurrentTab(1)" placeholder="请输入详细地址（省/直辖市+市/区+具体地址）" />
            </view>

            <view class="form-item one-sixth">
              <text class="form-label required">配偶状态</text>
              <el-select v-model="form.maritalStatus" @focus="setCurrentTab(1)" placeholder="请选择">
                <el-option 
                  v-for="item in dictData.spouse_status" 
                  :key="item.dictCode" 
                  :label="item.dictLabel" 
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </view>

            <view class="form-item">
              <text class="form-label">常联系家人</text>
              <el-input v-model="form.emergencyContact" @focus="setCurrentTab(1)" placeholder="例如：小女儿王大花" />
            </view>

            <view class="form-item full-width">
              <text class="form-label">居住情况</text>
              <el-select v-model="form.livingCondition" @focus="setCurrentTab(1)" placeholder="请选择">
                <el-option 
                  v-for="item in dictData.living_situation" 
                  :key="item.dictCode" 
                  :label="item.dictLabel" 
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </view>
          </view>
        </view>

        <view class="form-section" id="section-comm">
          <view class="section-title">沟通偏好</view>
          <view class="form-grid">
            <view class="form-item">
              <text class="form-label">喜欢的称呼</text>
              <el-input v-model="form.nickname" @focus="setCurrentTab(2)" placeholder="请输入称呼（可多填）" />
            </view>

            <view class="form-item">
              <text class="form-label">可理解语言</text>
              <el-input v-model="form.languages" @focus="setCurrentTab(2)" placeholder="普通话、东北话等（可多填）" />
            </view>

            <view class="form-item">
              <text class="form-label">语速偏好</text>
              <el-select v-model="form.speechRate" @focus="setCurrentTab(2)" placeholder="请选择">
                <el-option 
                  v-for="item in dictData.speech_sate_preference" 
                  :key="item.dictCode" 
                  :label="item.dictLabel" 
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </view>
          </view>
        </view>

        <view class="form-section" id="section-entertain">
          <view class="section-title">娱乐媒体偏好</view>
          <view class="form-grid">
            <view class="form-item">
              <text class="form-label">喜欢的内容</text>
              <el-input v-model="form.entertainmentContent" @focus="setCurrentTab(3)" placeholder="评书、越剧、二人转（可多填）" />
            </view>

            <view class="form-item">
              <text class="form-label">喜欢的歌手/人</text>
              <el-input v-model="form.favoriteSinger" @focus="setCurrentTab(3)" placeholder="例如：李谷一" />
            </view>

            <view class="form-item">
              <text class="form-label">年代偏好</text>
              <el-select v-model="form.eraPreference" @focus="setCurrentTab(3)" placeholder="请选择">
                <el-option label="50~70年代" value="50~70年代"></el-option>
                <el-option label="80~90年代" value="80~90年代"></el-option>
                <el-option label="现代" value="现代"></el-option>
              </el-select>
            </view>

            <view class="form-item">
              <text class="form-label">宗教信仰</text>
              <el-select v-model="form.religion" @focus="setCurrentTab(3)" placeholder="请选择">
                <el-option label="无" value="无"></el-option>
                <el-option label="佛教" value="佛教"></el-option>
                <el-option label="基督教" value="基督教"></el-option>
                <el-option label="伊斯兰教" value="伊斯兰教"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </view>
          </view>
        </view>

        <view class="form-section" id="section-health">
          <view class="section-title">健康状态</view>
          <view class="form-grid">
            <view class="form-item">
              <text class="form-label">慢性病情况</text>
              <el-input v-model="form.chronicDisease" @focus="setCurrentTab(4)" placeholder="例如：高血压" />
            </view>

            <view class="form-item">
              <text class="form-label">是否需要夜间陪伴</text>
              <el-select v-model="form.needNightCompanion" @focus="setCurrentTab(4)" placeholder="请选择">
                <el-option 
                  v-for="item in dictData.needs_nighttime_companion" 
                  :key="item.dictCode" 
                  :label="item.dictLabel" 
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </view>

            <view class="form-item">
              <text class="form-label">有无表达障碍</text>
              <el-select v-model="form.speechDisorder" @focus="setCurrentTab(4)" placeholder="请选择">
                <el-option 
                  v-for="item in dictData.speech_impairment" 
                  :key="item.dictCode" 
                  :label="item.dictLabel" 
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </view>
          </view>
        </view>

        <view class="form-section" id="section-media">
          <view class="section-title">多媒体记录</view>
          <view class="media-section new-media-section" :class="{ single: !form.personalVoice }">
            <view class="media-item">
              <div class="media-label label-outside">家人语音素材</div>
              <view class="new-upload-card">
                <view class="new-upload-card-header-inner">
                  <span class="file-count">文件数量 {{ form.familyVoiceFiles.length }}/3</span>
                  <button v-if="form.familyVoiceFiles.length > 0 && form.familyVoiceFiles.length < 3" class="add-btn" @click="uploadFile('familyVoiceFiles')">继续添加</button>
                </view>
                <view v-if="form.familyVoiceFiles.length === 0" class="new-file-upload-area upload-area-center">
                  <uni-icons type="music" size="48" color="#c0c4cc" />
                  <text class="upload-tip">点击上传文件</text>
                  <button class="upload-btn" @focus="setCurrentTab(5)" @click="uploadFile('familyVoiceFiles')">点击上传</button>
                </view>
                <view v-if="form.familyVoiceFiles.length > 0" class="new-uploaded-files">
                  <view 
                    v-for="(file, index) in form.familyVoiceFiles" 
                    :key="index" 
                    class="new-file-item"
                  >
                    <uni-icons type="music" size="32" color="#ffb300" />
                    <view class="file-info">
                      <div class="file-name">
                        <el-icon style="margin-right: 8px; color: #666;"><Document /></el-icon>
                        {{ file.name }}
                      </div>
                    </view>
                    <button class="remove-btn" @click="removeFile('familyVoiceFiles', index)">×</button>
                  </view>
                </view>
              </view>
            </view>
            <!-- <view class="media-item">
              <div class="media-label label-outside">本人录音</div>
              <view class="new-upload-card">
                <view class="new-upload-card-header-inner">
                  <span class="file-count">文件数量 {{ form.personalVoice ? 1 : 0 }}/1</span>
                </view>
                <view v-if="!form.personalVoice" class="new-file-upload-area upload-area-center">
                  <uni-icons type="music" size="48" color="#c0c4cc" />
                  <text class="upload-tip">点击上传文件</text>
                  <button class="upload-btn" @focus="setCurrentTab(5)" @click="uploadFile('personalVoice')">点击上传</button>
                </view>
                <view v-if="form.personalVoice" class="new-uploaded-files">
                  <view class="new-file-item">
                    <uni-icons type="music" size="32" color="#ffb300" />
                    <view class="file-info">
                      <div class="file-name">
                        <el-icon style="margin-right: 8px; color: #666;"><Document /></el-icon>
                        本人录音
                      </div>
                    </view>
                    <button class="remove-btn" @click="form.personalVoice = ''">×</button>
                  </view>
                </view>
              </view>
            </view> -->
          </view>
        </view>

        <view class="form-section" id="section-memory">
          <view class="section-title">个性记忆资料</view>
          <view class="form-grid">
            <view class="form-item">
              <text class="form-label">曾从事职业</text>
              <el-input v-model="form.career" @focus="setCurrentTab(6)" placeholder="例如：数学老师" />
            </view>

            <view class="form-item">
              <text class="form-label">年轻时/曾经住过城市</text>
              <el-input v-model="form.livedCities" @focus="setCurrentTab(6)" placeholder="例如：上海（可多填）" />
            </view>

            <view class="form-item full-width textarea-item">
              <text class="form-label">难忘的事</text>
              <view style="position: relative; width: 100%;">
                <el-input v-model="form.memorableEvent" @focus="setCurrentTab(6)" placeholder="例如：上山下乡" maxlength="100" type="textarea" :rows="3" />
                <view class="input-tip-inside">{{ form.memorableEvent.length }}/100</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="button-divider"></view>

      <view class="fixed-buttons">
        <el-button v-if="isFirstLogin" class="cancel-btn" @click="onLogout">退出</el-button>
        <el-button v-else class="cancel-btn" @click="onCancel">取消</el-button>
        <el-button class="confirm-btn" type="primary" :disabled="submitting" @click="onConfirm">确定</el-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { go } from '@/utils/nav.js';
import { provinceAndCityData } from 'element-china-area-data';
import { getDictData, getUserProfile, addUserProfile, updateUserProfile } from '@/api/pc/elderly';
import FileUploader from '@/utils/fileUpload.js';
import { useUserStore } from '@/store/modules/user';
import { Document } from '@element-plus/icons-vue';
import RemindWebSocket from '@/components/RemindWebSocket.vue';
import { convertEmptyAndUndefinedToNull } from '@/utils/common.js'; 
import { ArrowLeft } from '@element-plus/icons-vue';
const userStore = useUserStore();

const currentTab = ref(0);

const dictData = reactive({
  gender: [],
  spouse_status: [],
  living_situation: [],
  speech_sate_preference: [],
  speech_impairment: [],
  needs_nighttime_companion: []
});

const navItems = ref([
  { title: '基本信息', anchor: 'section-basic' },
  { title: '家庭关系', anchor: 'section-family' },
  { title: '沟通偏好', anchor: 'section-comm' },
  { title: '娱乐媒体偏好', anchor: 'section-entertain' },
  { title: '健康状态', anchor: 'section-health' },
  { title: '多媒体记录', anchor: 'section-media' },
  { title: '个性记忆资料', anchor: 'section-memory' }
]);

const form = reactive({
  name: '',
  gender: '',
  nativePlace: '',
  age: '',
  birthDate: '',
  education: '',
  avatar: '',
  address: '',
  maritalStatus: '',
  emergencyContact: '',
  livingCondition: '',
  nickname: '',
  languages: '',
  speechRate: null,
  entertainmentContent: '',
  favoriteSinger: '',
  eraPreference: '',
  religion: '',
  chronicDisease: '',
  needNightCompanion: '',
  speechDisorder: '',
  familyVoiceFiles: [],
  personalVoice: '',
  career: '',
  livedCities: '',
  memorableEvent: ''
});

const primaryId = ref(null);
const isLoading = ref(true);
const isFirstLogin = ref(false); // 是否是初次登录

const switchTab = (index) => {
  currentTab.value = index;
  const anchor = navItems.value[index].anchor;
  const el = document.getElementById(anchor);
  if (el) {
    el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }
};

// 获取头像显示源
const getAvatarSrc = (avatarData) => {
  if (!avatarData) return '';
  
  // 如果是对象且包含fileBase64（修改模式：从个人信息获取）
  if (typeof avatarData === 'object' && avatarData.fileBase64) {
    return `data:${avatarData.mimeType || 'image/jpeg'};base64,${avatarData.fileBase64}`;
  }
  
  // 如果已经是base64格式，直接返回（创建模式：文件上传返回值）
  if (typeof avatarData === 'string' && avatarData.startsWith('data:image/')) {
    return avatarData;
  }
  
  // 如果是base64字符串但没有data:前缀，添加前缀
  if (typeof avatarData === 'string' && !avatarData.startsWith('data:')) {
    return `data:image/jpeg;base64,${avatarData}`;
  }
  
  // 没有有效头像数据时返回空字符串，让模板显示默认人像轮廓
  return '';
};

const chooseAvatar = async () => {
  try {
    const chooseResult = await new Promise((resolve, reject) => {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: resolve,
        fail: reject
      });
    });

    const file = chooseResult.tempFiles[0];
    
    uni.showLoading({ title: '上传头像中...' });
    
    // 个人信息填写模式：mode=1，不传入relativeId
    const uploadResponse = await FileUploader.uploadAvatar(file, userStore.id, undefined, 1);
    
    uni.hideLoading();
    
    // 处理上传响应：FileUploader直接返回文件数据对象
    if (uploadResponse && uploadResponse.fileData) {
      // 保存文件数据对象
      form.avatar = uploadResponse.fileData;
      // 保存到本地存储，防止F5刷新后丢失
      uni.setStorageSync('user_avatar_temp', uploadResponse.fileData);
      console.log('头像上传成功，保存的数据:', form.avatar);
    } else if (uploadResponse && uploadResponse.fileBase64) {
      // 兼容处理：如果直接返回文件对象
      form.avatar = uploadResponse;
      // 保存到本地存储，防止F5刷新后丢失
      uni.setStorageSync('user_avatar_temp', uploadResponse);
      console.log('头像上传成功，保存的数据:', form.avatar);
    } else {
      console.error('上传响应格式异常:', uploadResponse);
      uni.showToast({ title: '上传响应格式异常', icon: 'none' });
      return;
    }
    
    uni.showToast({ title: '头像上传成功', icon: 'success' });
    
    // 触发全局头像更新事件，通知侧边栏等组件更新头像
    uni.$emit('avatar-updated', form.avatar);
  } catch (error) {
    uni.hideLoading();
    console.error('头像上传失败:', error);
    // uni.showToast({ title: '头像上传失败，请重试', icon: 'none' });
  }
};

const uploadFile = async (type) => {
  try {
    const chooseResult = await new Promise((resolve, reject) => {
      uni.chooseFile({
        count: 1,
        type: 'audio',
        success: resolve,
        fail: reject
      });
    });

    const file = chooseResult.tempFiles[0];
    
    uni.showLoading({ title: '上传中...' });
    
    let fileUrl;
    if (type === 'familyVoiceFiles') {
      // 家人语音：个人信息填写模式，直接调用底层并传入 context='relative'，mode=1
      fileUrl = await FileUploader.uploadRelativeFile(file, userStore.id, undefined, 'relative', 1);
    } else if (type === 'personalVoice') {
      // 本人录音：个人信息填写模式，mode=1
      fileUrl = await FileUploader.uploadAudio(file, userStore.id, undefined, undefined, 1);
    }
    
    uni.hideLoading();
    
    if (type === 'familyVoiceFiles') {
      form.familyVoiceFiles.push({
        name: file.name,
        size: formatFileSize(file.size),
        url: fileUrl
      });
      uni.showToast({ title: '家人语音上传成功', icon: 'success' });
    } else if (type === 'personalVoice') {
      form.personalVoice = fileUrl;
      uni.showToast({ title: '本人录音上传成功', icon: 'success' });
    }
  } catch (error) {
    try { uni.hideLoading(); } catch(e) {}
    // 取消选择时静默返回，不提示错误
    if (error && typeof error === 'object' && String(error.errMsg || '').includes('cancel')) {
      return;
    }
    console.error('文件上传失败:', error);
    uni.showToast({ title: '上传失败，请重试', icon: 'none' });
  }
};

const removeFile = (type, index) => {
  form[type].splice(index, 1);
};

const formatFileSize = (bytes) => {
  if (bytes < 1024) return bytes + 'B';
  else if (bytes < 1048576) return (bytes / 1024).toFixed(1) + 'KB';
  else return (bytes / 1048576).toFixed(1) + 'MB';
};

const onCancel = () => {
  go('/pages/pc/index');
};

// 退出登录方法
const onLogout = async () => {
  try {
    uni.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: async (res) => {
        if (res.confirm) {
          uni.showLoading({ title: '退出中...' });
          
          // 调用用户store的退出方法
          await userStore.logOut();
          
          uni.hideLoading();
          uni.showToast({ title: '已退出登录', icon: 'success' });
          
          // 跳转到登录页面
          go('/pages/pc/login', { replace: true });
        }
      }
    });
  } catch (error) {
    uni.hideLoading();
    console.error('退出登录失败:', error);
    uni.showToast({ title: '退出失败，请重试', icon: 'none' });
  }
};

const onConfirm = async () => {
  // 基础必填校验
  if (!form.name) {
    return uni.showToast({ title: '请输入姓名', icon: 'none' });
  }
  if (!form.gender) {
    return uni.showToast({ title: '请选择性别', icon: 'none' });
  }
  if (!form.nativePlace) {
    return uni.showToast({ title: '请输入籍贯', icon: 'none' });
  }
  if (!form.age) {
    return uni.showToast({ title: '请输入年龄', icon: 'none' });
  }
  if (!form.birthDate) {
    return uni.showToast({ title: '请选择出生日期', icon: 'none' });
  }
  if (!form.education) {
    return uni.showToast({ title: '请选择文化程度', icon: 'none' });
  }
  if (!form.address) {
    return uni.showToast({ title: '请输入居住地址', icon: 'none' });
  }
  if (!form.maritalStatus) {
    return uni.showToast({ title: '请选择配偶状态', icon: 'none' });
  }

  // 统一长度/范围校验
  const len = (v) => (v == null ? 0 : String(v).length);
  const checkLen = (v, max, msg) => {
    if (v && len(v) > max) { uni.showToast({ title: msg, icon: 'none' }); return false; }
    return true;
  };
  const ageNum = Number(form.age);
  if (!Number.isFinite(ageNum) || ageNum < 0 || ageNum > 120) {
    return uni.showToast({ title: '年龄需为0-120之间的数字', icon: 'none' });
  }
  if (!checkLen(form.name, 10, '姓名最多10个字符')) return;
  if (!checkLen(form.gender, 2, '性别最多2个字符')) return;
  const hometownStr = Array.isArray(form.nativePlace) ? form.nativePlace.join('/') : form.nativePlace;
  if (!checkLen(hometownStr, 50, '籍贯最多50个字符')) return;
  if (!checkLen(form.address, 50, '居住地最多50个字符')) return;
  if (!checkLen(form.education, 10, '文化程度最多10个字符')) return;

  // 其余文本100字符上限（选填）
  const optional100 = [
    form.nickname, form.languages, form.entertainmentContent, form.favoriteSinger,
    form.eraPreference, form.religion, form.chronicDisease, form.career,
    form.livedCities, form.memorableEvent
  ];
  for (const v of optional100) {
    if (v && len(v) > 100) {
      return uni.showToast({ title: '文本内容最多100个字符', icon: 'none' });
    }
  }

  const submitData = {
    id: primaryId.value,
    userId: userStore.id,
    name: form.name,
    gender: form.gender,
    age: form.age,
    birthDate: form.birthDate,
    hometown: form.nativePlace ? form.nativePlace.join('/') : '',
    educationLevel: form.education,
    livecity: form.address,
    spouseStatus: form.maritalStatus,
    frequentFamilyContacts: form.emergencyContact,
    livingSituation: form.livingCondition,
    preferredName: form.nickname,
    understandableLanguages: form.languages,
    speechRatePreference: form.speechRate,
    preferredContent: form.entertainmentContent,
    favoriteMusicians: form.favoriteSinger,
    preferredEra: form.eraPreference,
    religiousBelief: form.religion,
    chronicDiseases: form.chronicDisease,
    // 注意：字典和数据库都是 0=是,1=否，直接转为数字即可
    speechImpairment: form.speechDisorder === '0' ? 0 : (form.speechDisorder === '1' ? 1 : null),
    needsNighttimeCompanion: form.needNightCompanion === '0' ? 0 : (form.needNightCompanion === '1' ? 1 : null),
    familyVideoMaterials: null, // 统一为对象数组风格（暂无采集，保持 null）
    familyAudioMaterials: form.familyVoiceFiles && form.familyVoiceFiles.length > 0
      ? form.familyVoiceFiles
          .map(f => {
            const u = f?.url
            if (!u) return null
            if (typeof u === 'object') {
              const d = u.fileData || u
              return {
                fileBase64: d.fileBase64 || u.fileUrl || '',
                fileName: d.fileName || f.name || 'audio',
                mimeType: d.mimeType || 'audio/mpeg'
              }
            }
            if (typeof u === 'string') {
              const mime = u.startsWith('data:') && u.includes(';') ? u.slice(5, u.indexOf(';')) : 'audio/mpeg'
              return { fileBase64: u, fileName: f.name || 'audio', mimeType: mime }
            }
            return null
          })
          .filter(Boolean)
      : null,
    personalRecordings: form.personalVoice
      ? [{
          fileBase64: typeof form.personalVoice === 'object'
            ? (form.personalVoice.fileBase64 || form.personalVoice.fileUrl || '')
            : form.personalVoice,
          fileName: 'personal-recording',
          mimeType: 'audio/mpeg'
        }]
      : null,
    previousOccupation: form.career,
    citiesLivedInYoungAge: form.livedCities,
    mostUnforgettableMemory: form.memorableEvent,
    // 添加头像数据
    personalPhotos: form.avatar ? (typeof form.avatar === 'object' ? [form.avatar] : [{
      fileBase64: form.avatar,
      fileName: 'avatar.jpg',
      mimeType: 'image/jpeg'
    }]) : null
  };

  // 将空字符串转换为null
  const processedSubmitData = convertEmptyAndUndefinedToNull(submitData);

  try {
    uni.showLoading({ title: '提交中...' });
    
    let response;
    if (primaryId.value) {
      response = await updateUserProfile(processedSubmitData);
      console.log('更新用户画像响应:', response);
    } else {
      response = await addUserProfile(processedSubmitData);
      console.log('新增用户画像响应:', response);
    }

    uni.hideLoading();
    
    if (response.code === 200) {
      // 保存成功后清除本地存储的临时头像数据
      try {
        uni.removeStorageSync('user_avatar_temp');
        console.log('已清除本地存储的临时头像数据');
      } catch (error) {
        console.log('清除本地存储失败:', error);
      }
      
      uni.showToast({ title: '信息保存成功', icon: 'success' });
      
      // 保存成功后，清除用户画像缓存，强制重新加载
      userStore.clearUserProfileCache();
      
      // 触发全局头像更新事件
      if (form.avatar) {
        uni.$emit('avatar-updated', form.avatar);
      }
      
      go('/pages/pc/index');
    } else {
      uni.showToast({ title: response.msg || '保存失败', icon: 'none' });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('保存用户画像失败:', error);
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  }
};

onMounted(async () => {
  try {
    isLoading.value = true;
    
    const dictTypes = [
      'gender',
      'spouse_status', 
      'living_situation',
      'speech_sate_preference',
      'speech_impairment',
      'needs_nighttime_companion'
    ];
    
    const promises = dictTypes.map(type => getDictData(type));
    const results = await Promise.all(promises);
    
    dictTypes.forEach((type, index) => {
      if (results[index].code === 200 && results[index].data) {
        dictData[type] = results[index].data;
      }
    });
    
    console.log('字典数据加载完成:', dictData);
    
    const userId = userStore.id;
    if (userId) {
      // 使用更安全的方式处理用户画像获取，完全屏蔽错误显示
      let userProfileResponse = null;
      try {
        userProfileResponse = await getUserProfile(userId);
      } catch (error) {
        // 完全静默处理，不显示任何错误信息
        userProfileResponse = null;
      }
      
      // 检查响应是否有效
      if (userProfileResponse && 
          userProfileResponse.code === 200 && 
          userProfileResponse.data && 
          userProfileResponse.data !== null &&
          typeof userProfileResponse.data === 'object') {
        const userData = userProfileResponse.data;
        
        primaryId.value = userData.id;
        
        form.name = userData.name || '';
        form.gender = userData.gender || '';
        form.age = userData.age || '';
        form.birthDate = userData.birthDate || '';
        form.education = userData.educationLevel || '';
        form.address = userData.livecity || '';
        form.maritalStatus = userData.spouseStatus || '';
        form.emergencyContact = userData.frequentFamilyContacts || '';
        form.livingCondition = userData.livingSituation || '';
        form.nickname = userData.preferredName || '';
        form.languages = userData.understandableLanguages || '';
        form.speechRate = userData.speechRatePreference || '';
        form.entertainmentContent = userData.preferredContent || '';
        form.favoriteSinger = userData.favoriteMusicians || '';
        form.eraPreference = userData.preferredEra || '';
        form.religion = userData.religiousBelief || '';
        form.chronicDisease = userData.chronicDiseases || '';
        // 注意：数据库存储 0=是,1=否，字典中也是 "是"="0","否"="1"，直接转为字符串即可
        form.needNightCompanion = userData.needsNighttimeCompanion !== null && userData.needsNighttimeCompanion !== undefined ? String(userData.needsNighttimeCompanion) : '';
        form.speechDisorder = userData.speechImpairment !== null && userData.speechImpairment !== undefined ? String(userData.speechImpairment) : '';
        form.career = userData.previousOccupation || '';
        form.livedCities = userData.citiesLivedInYoungAge || '';
        form.memorableEvent = userData.mostUnforgettableMemory || '';
        
        // 加载头像数据
        if (userData.personalPhotos && userData.personalPhotos.length > 0) {
          const photoData = userData.personalPhotos[0];
          // 保存完整的头像数据对象，包含fileBase64
          form.avatar = photoData;
        }
        
        // 如果没有从服务器加载到头像，尝试从本地存储恢复临时头像
        if (!form.avatar) {
          try {
            const tempAvatar = uni.getStorageSync('user_avatar_temp');
            if (tempAvatar) {
              form.avatar = tempAvatar;
              console.log('从本地存储恢复头像数据:', tempAvatar);
            }
          } catch (error) {
            console.log('本地存储中没有临时头像数据');
          }
        }
         
        if (userData.hometown) {
          form.nativePlace = userData.hometown.split('/');
        }
         
        if (Array.isArray(userData.familyAudioMaterials) && userData.familyAudioMaterials.length > 0) {
          form.familyVoiceFiles = userData.familyAudioMaterials
            .filter(Boolean)
            .map(d => ({
              name: d.fileName || '音频文件',
              size: '未知',
              url: { fileUrl: d.fileBase64 || '', fileData: d }
            }));
        } else {
          form.familyVoiceFiles = [];
        }
        
        if (Array.isArray(userData.personalRecordings) && userData.personalRecordings.length > 0) {
          const d = userData.personalRecordings[0]
          form.personalVoice = d?.fileBase64 || ''
        } else {
          form.personalVoice = ''
        }
        
        console.log('用户画像数据加载完成:', userData);
        console.log('主键ID:', primaryId.value);
        
        // 判断是否是初次登录
        isFirstLogin.value = false;
      } else {
        // 用户画像不存在，静默处理，不显示任何错误信息
        console.log('用户画像数据不存在，将创建新的画像');
        
        // 判断是否是初次登录
        isFirstLogin.value = true;
        
        // 尝试从本地存储恢复临时头像
        try {
          const tempAvatar = uni.getStorageSync('user_avatar_temp');
          if (tempAvatar) {
            form.avatar = tempAvatar;
            console.log('从本地存储恢复头像数据:', tempAvatar);
          }
        } catch (error) {
          console.log('本地存储中没有临时头像数据');
        }
      }
    }
  } catch (error) {
    // 其他系统错误也不记录，避免在云服务中报错
    console.log('系统初始化完成');
  } finally {
    isLoading.value = false;
  }
});

const setCurrentTab = (idx) => {
  currentTab.value = idx;
};

watch(() => form.birthDate, (newDate) => {
  if (newDate) {
    const birthDate = new Date(newDate);
    const currentDate = new Date();
    const age = currentDate.getFullYear() - birthDate.getFullYear();
    const monthDiff = currentDate.getMonth() - birthDate.getMonth();
    
    if (monthDiff < 0 || (monthDiff === 0 && currentDate.getDate() < birthDate.getDate())) {
      form.age = age - 1;
    } else {
      form.age = age;
    }
  } else {
    form.age = '';
  }
});
</script>

<style scoped>
/* 页面背景 */
.pc-page-bg {
  /* 渐变色更贴近图片，左上淡蓝，右下淡粉白 */
  background: linear-gradient(180deg, #eaf6ff 0%, #f8fafd 20%, #fdf6f6 100%);
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  gap: 20px;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1976ed;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  font-size: 16px;
  color: #666;
  font-weight: 500;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 主内容区样式 */
.main-content {
  padding: 30px 50px;
  flex: 1;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.main-header {
  height: 64px;
  display: flex;
  align-items: center;
  padding-left: 32px;
  font-size: 32px;
  font-weight: 600;
  border-bottom: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.back-btn {
  font-size: 32px;
  color: #222;
  cursor: pointer;
  margin-right: 18px;
  font-weight: 700;
}

/* 页面标题 */
.page-title {
  color: #333;
}

/* 主容器 */
.main-container {
  flex: 1;
  display: flex;
  overflow-y: auto;
  min-height: 0;
  gap: 30px;
  padding-right: 200px;
}

/* 左侧导航 */
.left-nav {
  width: 200px;
  padding: 20px 0;
  border-right: 1px solid #f0f0f0;
  flex-shrink: 0;
}

/* 自定义左侧导航栏样式 */
.custom-nav-list {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  margin-top: 30px;
}
.custom-nav-item {
  width: 160px;
  text-align: right;
  font-size: 16px;
  color: #222;
  line-height: 48px;
  padding-right: 18px;
  cursor: pointer;
  border-right: 3px solid transparent;
  transition: color 0.2s, border-color 0.2s;
}
.custom-nav-item.active {
  color: #1976ed;
  font-weight: bold;
  border-right: 3px solid #1976ed;
  background: none;
}

/* 右侧表单内容 */
.form-content {
  flex: 1;
  padding: 30px;
  min-height: 600px;
  overflow-y: auto; /* 添加滚动条 */
  max-height: 80vh; /* 限制最大高度 */
}

/* 表单区块样式调整 */
.form-section {
  margin-bottom: 30px;
}

/* 表单区块标题 */
.section-title {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f5f5f5;
}

/* 表单网格布局 */
.form-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 20px 30px;
}

/* 表单项目 */
.form-item {
  display: flex;
  flex-direction: column;
  grid-column: span 2;
}

.form-item.one-sixth {
  grid-column: span 1;
}

.form-item.full-width {
  grid-column: span 6;
}

/* 表单标签 */
.form-label {
  font-size: 26rpx;
  color: #606266;
  margin-bottom: 8px;
  font-weight: bold;
}

/* 必填项标识 */
.form-label.required::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

/* 头像上传区域 */
.avatar-item {
  grid-column: 5 / span 2;
  grid-row: span 2;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-start;
  gap: 12px;
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 12px;
  width: 100%;
}

.avatar-container {
  width: 100px;
  height: 100px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  overflow: hidden;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-btn-container {
  width: 100%;
  display: flex;
  justify-content: flex-start;
}

.upload-btn {
  width: 100px;
  height: 32px;
  background: #fff;
  color: #409eff;
  border: 1px solid #409eff;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  margin: 0;
  padding: 0;
  text-align: center;
  display: block;
}

.upload-btn:hover {
  background: #409eff;
  color: #fff;
}

/* 多媒体文件上传区域 */
.media-section {
  margin-top: 20px;
  display: flex;
  gap: 30px;
}

.media-item {
  flex: 1;
  min-width: 0;
  margin-bottom: 0;
}

.media-label {
  font-size: 26rpx;
  color: #606266;
  margin-bottom: 15px;
  display: block;
}

/* 半行宽度表单项 */
.form-item.half-width {
  grid-column: span 3;
}

/* 难忘的事字数统计在输入框内部右下角 */
.textarea-item {
  position: relative;
}
.input-tip-inside {
  position: absolute;
  right: 12px;
  bottom: 8px;
  font-size: 12px;
  color: #999;
  background: #fff;
  padding: 0 4px;
  pointer-events: none;
}

/* 分割线样式 */
.button-divider {
  margin-top: 50px;
  height: 1px;
  background: #f0f0f0;
}

/* 固定按钮组样式 */
.fixed-buttons {
  display: flex;
  gap: 16px;
  background: transparent;
  padding: 24px 48px;
  justify-content: flex-end;
  flex-shrink: 0;
}

.cancel-btn {
  background: #fff;
  color: #888;
  border: 1px solid #e3e7ed;
  border-radius: 8px;
  font-size: 16px;
  padding: 0 32px;
  height: 40px;
  cursor: pointer;
}

.confirm-btn {
  background: #1976ed;
  color: #fff;
  border-radius: 8px;
  font-size: 16px;
  padding: 0 32px;
  height: 40px;
  border: none;
  cursor: pointer;
  font-weight: 600;
}

/* Element Plus 输入框和下拉选择框样式覆盖 - 完整版本 */
:deep(.el-input__wrapper) {
  height: 48px !important;
  border-radius: 4px;
}

:deep(.el-input__inner) {
  height: 48px !important;
  line-height: 48px !important;
  font-size: 14px;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa !important;
  border-color: #e4e7ed !important;
}

:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #f5f7fa !important;
  color: #c0c4cc !important;
  cursor: not-allowed;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-select .el-input) {
  height: 48px !important;
}

:deep(.el-select .el-input__wrapper) {
  height: 48px !important;
  border-radius: 4px;
}

:deep(.el-select .el-input__inner) {
  height: 48px !important;
  line-height: 48px !important;
  font-size: 14px;
}

:deep(.el-select__wrapper) {
  height: 48px !important;
}

:deep(.el-textarea__inner) {
  min-height: 80px;
  font-size: 14px;
  padding: 12px 15px;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-date-editor .el-input__wrapper) {
  height: 48px !important;
}

:deep(.el-date-editor .el-input__inner) {
  height: 48px !important;
  line-height: 48px !important;
}

/* uni-data-picker 样式覆盖 */
:deep(.uni-data-picker) {
  width: 100%;
}

:deep(.uni-data-picker .uni-input-wrapper) {
  height: 48px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

:deep(.uni-data-picker .uni-input-input) {
  height: 48px;
  line-height: 48px;
  font-size: 14px;
  padding: 0 15px;
}

/* Element Plus 级联选择器样式 */
:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-cascader .el-input__wrapper) {
  height: 48px !important;
}

:deep(.el-cascader .el-input__inner) {
  height: 48px !important;
  line-height: 48px !important;
}

.upload-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
  padding: 0 0 16px 0;
  margin-bottom: 0;
  min-width: 320px;
  flex: 1;
  display: flex;
  flex-direction: column;
}
.upload-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 16px 0 16px;
  border-bottom: 1px solid #f0f0f0;
  min-height: 40px;
}
.file-count {
  font-size: 13px;
  color: #999;
}
.add-btn {
  all: unset;
  background: none !important;
  border: none !important;
  outline: none !important;
  color: #1976ed !important;
  font-size: 14px;
  cursor: pointer;
  padding: 0 !important;
  margin: 0 !important;
  border-radius: 0 !important;
  transition: color 0.2s;
  font-weight: 500;
  position: absolute;
  right: 20px;
  top: 16px;
  text-decoration: none !important;
  box-shadow: none !important;
  -webkit-appearance: none !important;
  -moz-appearance: none !important;
  appearance: none !important;
  display: inline-block;
  line-height: 1;
}
.add-btn:hover {
  background: #f0f7ff;
}
.file-upload-area.no-border {
  border: none;
  box-shadow: none;
  background: transparent;
  padding: 32px 0 0 0;
}
.uploaded-files {
  margin: 0 16px;
  border: none;
  background: none;
  padding: 0;
}
.file-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}
.file-item:last-child {
  border-bottom: none;
}
.file-name {
  flex: 1;
  font-size: 14px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.file-size {
  font-size: 12px;
  color: #999;
  margin-right: 8px;
}
.remove-btn {
  background: #f56c6c;
  color: #fff;
  border: none;
  border-radius: 3px;
  padding: 4px 8px;
  font-size: 12px;
  cursor: pointer;
}
.remove-btn:hover {
  background: #f78989;
}
.new-media-section {
  display: flex;
  gap: 32px;
}
.new-media-section.single .media-item {
  flex: 0 0 50%;
  max-width: 50%;
}
.new-upload-card {
  background: #fafbfc;
  border: 1.5px dashed #d8d8d8;
  border-radius: 12px;
  box-shadow: none;
  padding: 0 0 18px 0;
  min-width: 320px;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 280px;
  transition: border-color 0.2s;
}
.new-upload-card-header-inner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 16px 0 16px;
  min-height: 40px;
  font-size: 15px;
  font-weight: 500;
  width: 100%;
  position: relative;
}
.media-label {
  color: #222;
  font-size: 16px;
  font-weight: 600;
}
.file-count {
  color: #999;
  font-size: 13px;
  flex-shrink: 0;
}
.add-btn {
  background: none;
  border: none;
  color: #1976ed;
  font-size: 14px;
  cursor: pointer;
  padding: 0;
  border-radius: 0;
  transition: color 0.2s;
  font-weight: 500;
  flex-shrink: 0;
}
.add-btn:disabled {
  color: #ccc;
  cursor: not-allowed;
}
.add-btn:hover:enabled {
  background: #f0f7ff;
}
.new-file-upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: none;
  background: transparent;
  padding: 36px 0 0 0;
  min-height: 120px;
}
.upload-tip {
  color: #bdbdbd;
  font-size: 15px;
  margin: 12px 0 10px 0;
}
.upload-btn {
  width: 120px;
  height: 36px;
  background: #fff;
  color: #1976ed;
  border: 1.5px solid #1976ed;
  border-radius: 6px;
  font-size: 15px;
  cursor: pointer;
  margin: 0;
  padding: 0;
  text-align: center;
  display: block;
  transition: background 0.2s, color 0.2s;
  font-weight: 500;
}
.upload-btn:disabled {
  color: #ccc;
  border-color: #eee;
  cursor: not-allowed;
}
.upload-btn:hover:enabled {
  background: #1976ed;
  color: #fff;
}
.new-uploaded-files {
  margin: 0 18px;
  background: none;
  padding: 0;
  margin-top: 16px;
}
.new-file-item {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 10px 0 8px 0;
  border-bottom: 1px solid #f0f0f0;
  min-height: 44px;
}
.new-file-item:last-child {
  border-bottom: none;
}
.file-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-width: 0;
}
.file-name {
  font-size: 15px;
  color: #333;
  font-weight: 500;
  line-height: 1.2;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.file-size {
  font-size: 13px;
  color: #bdbdbd;
  margin-top: 2px;
  line-height: 1.1;
}
.remove-btn {
  background: #f3f3f3;
  color: #bbb;
  border: none;
  border-radius: 50%;
  width: 28px;
  height: 28px;
  font-size: 18px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  transition: background 0.2s, color 0.2s;
}
.remove-btn:hover {
  background: #f56c6c;
  color: #fff;
}

.label-outside {
  font-size: 16px;
  font-weight: 600;
  color: #222;
  margin-bottom: 8px;
  margin-left: 2px;
}
.upload-area-center {
  align-items: center;
  justify-content: center;
  min-height: 180px;
}

/* ===== 平板适配样式 ===== */

/* 平板竖屏适配 (768px - 1024px) */
@media screen and (min-width: 768px) and (max-width: 1024px) and (orientation: portrait) {
  .main-content {
    padding: 20px 30px;
  }
  
  .main-container {
    gap: 20px;
    padding-right: 0;
  }
  
  .left-nav {
    width: 160px;
    padding: 15px 0;
  }
  
  .custom-nav-item {
    width: 140px;
    font-size: 15px;
    line-height: 44px;
    padding-right: 15px;
  }
  
  .form-content {
    padding: 20px;
    max-height: 75vh;
  }
  
  .section-title {
    font-size: 20px;
    margin-bottom: 15px;
  }
  
  /* 控制表单标签字体大小 */
  .form-label {
    font-size: 14px !important;
    line-height: 1.4;
  }
  
  .form-grid {
    grid-template-columns: repeat(4, 1fr);
    gap: 15px 20px;
  }
  
  .form-item {
    grid-column: span 2;
  }
  
  .form-item.full-width {
    grid-column: span 4;
  }
  
  .form-item.half-width {
    grid-column: span 2;
  }
  
  /* 基本信息部分在窄屏时的特殊布局 */
  #section-basic .form-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 15px 20px;
  }
  
  #section-basic .form-item {
    grid-column: span 1;
  }
  
  #section-basic .form-item[style*="grid-column: span 2"] {
    grid-column: span 2;
  }
  
  #section-basic .avatar-item {
    grid-column: 1 / span 3;
    grid-row: 1;
    align-items: flex-start;
    order: -1;
  }
  
  /* 确保其他表单项在头像下方 */
  #section-basic .form-item:not(.avatar-item) {
    order: 1;
  }
  
  #section-basic .avatar-container {
    width: 80px;
    height: 80px;
  }
  
  #section-basic .upload-btn {
    width: 80px;
    height: 30px;
    font-size: 13px;
  }
  
  .new-media-section {
    flex-direction: column;
    gap: 20px;
  }
  
  .new-upload-card {
    min-width: auto;
    min-height: 220px;
  }
  
}

/* 平板横屏适配 (768px - 1024px) */
@media screen and (min-width: 768px) and (max-width: 1024px) and (orientation: landscape) {
  .main-content {
    padding: 15px 25px;
  }
  
  .main-container {
    gap: 15px;
    padding-right: 0;
  }
  
  .left-nav {
    width: 140px;
    padding: 10px 0;
  }
  
  .custom-nav-list {
    margin-top: 20px;
    gap: 6px;
  }
  
  .custom-nav-item {
    width: 120px;
    font-size: 14px;
    line-height: 40px;
    padding-right: 12px;
  }
  
  .form-content {
    padding: 15px;
    max-height: 70vh;
  }
  
  .section-title {
    font-size: 18px;
    margin-bottom: 12px;
  }
  
  /* 控制表单标签字体大小 */
  .form-label {
    font-size: 13px !important;
    line-height: 1.4;
  }
  
  .form-grid {
    grid-template-columns: repeat(6, 1fr);
    gap: 12px 15px;
  }
  
  .form-item {
    grid-column: span 2;
  }
  
  .form-item.one-sixth {
    grid-column: span 1;
  }
  
  .form-item.full-width {
    grid-column: span 6;
  }
  
  .form-item.half-width {
    grid-column: span 3;
  }
  
  .avatar-item {
    grid-column: 5 / span 2;
    grid-row: span 2;
  }
  
  .avatar-container {
    width: 70px;
    height: 70px;
  }
  
  .upload-btn {
    width: 70px;
    height: 28px;
    font-size: 12px;
  }
  
  .new-media-section {
    gap: 20px;
  }
  
  .new-upload-card {
    min-height: 200px;
  }
  
  .new-upload-card-header-inner {
    padding: 12px 12px 0 12px;
    font-size: 14px;
  }
  
  .upload-tip {
    font-size: 14px;
    margin: 10px 0 8px 0;
  }
  
  .upload-btn {
    width: 100px;
    height: 32px;
    font-size: 14px;
  }
  
  .new-file-item {
    padding: 8px 0 6px 0;
    min-height: 40px;
  }
  
  .file-name {
    font-size: 14px;
  }
  
}

/* 大平板适配 (1024px - 1366px) */
@media screen and (min-width: 1024px) and (max-width: 1366px) {
  .main-content {
    padding: 25px 40px;
  }
  
  .main-container {
    gap: 25px;
    padding-right: 180px;
  }
  
  .left-nav {
    width: 180px;
  }
  
  .custom-nav-item {
    width: 150px;
    font-size: 15px;
    line-height: 46px;
    padding-right: 16px;
  }
  
  .form-content {
    padding: 25px;
    max-height: 78vh;
  }
  
  .form-grid {
    gap: 18px 25px;
  }
  
  .new-media-section {
    gap: 25px;
  }
  
  .new-upload-card {
    min-height: 250px;
  }
  
  /* 基本信息区块特殊布局 */
  #section-basic .form-grid {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    gap: 18px 25px;
  }
  #section-basic .avatar-item {
    grid-column: 1 / span 6 !important;
    grid-row: 1;
    align-items: flex-start;
    order: -1;
    margin-bottom: 10px;
  }
  #section-basic .form-item.native-place {
    grid-column: 1 / span 6 !important;
    order: 1;
  }
  #section-basic .form-item.age,
  #section-basic .form-item.birth-date {
    grid-column: span 3;
    order: 2;
  }
  #section-basic .form-item.education {
    grid-column: 1 / span 6 !important;
    order: 3;
  }
  /* 其他表单项默认一行 */
  /* 多媒体记录区块上下两整行布局 */
  .new-media-section {
    flex-direction: column;
    flex-wrap: nowrap;
    gap: 25px;
  }
  .new-media-section .media-item {
    flex: none;
    min-width: 0;
    max-width: 100%;
    width: 100%;
    margin-bottom: 0;
  }
}

/* 中等窄屏适配 (768px - 900px) */
@media screen and (min-width: 768px) and (max-width: 900px) {
  /* 基本信息部分在中等窄屏时的特殊布局 */
  #section-basic .form-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 15px 20px;
  }
  
  #section-basic .form-item {
    grid-column: span 1;
  }
  
  #section-basic .form-item[style*="grid-column: span 2"] {
    grid-column: span 2;
  }
  
  #section-basic .avatar-item {
    grid-column: 1 / span 3;
    grid-row: 1;
    align-items: flex-start;
    order: -1;
  }
  
  /* 确保其他表单项在头像下方 */
  #section-basic .form-item:not(.avatar-item) {
    order: 1;
  }
  
  #section-basic .avatar-container {
    width: 80px;
    height: 80px;
  }
  
  #section-basic .upload-btn {
    width: 80px;
    height: 30px;
    font-size: 13px;
  }
}

/* 平板通用优化 */
@media screen and (max-width: 1024px) {
  /* 控制表单标签字体大小，避免rpx单位缩放问题 */
  .form-label {
    font-size: 14px !important;
    line-height: 1.4;
  }
  
  /* 优化表单输入框在平板上的触摸体验 */
  :deep(.el-input__wrapper) {
    height: 44px !important;
  }
  
  :deep(.el-input__inner) {
    height: 44px !important;
    line-height: 44px !important;
    font-size: 16px; /* 增大字体便于触摸 */
  }
  
  :deep(.el-select .el-input__wrapper) {
    height: 44px !important;
  }
  
  :deep(.el-select .el-input__inner) {
    height: 44px !important;
    line-height: 44px !important;
    font-size: 16px;
  }
  
  :deep(.el-date-editor .el-input__wrapper) {
    height: 44px !important;
  }
  
  :deep(.el-date-editor .el-input__inner) {
    height: 44px !important;
    line-height: 44px !important;
    font-size: 16px;
  }
  
  :deep(.el-cascader .el-input__wrapper) {
    height: 44px !important;
  }
  
  :deep(.el-cascader .el-input__inner) {
    height: 44px !important;
    line-height: 44px !important;
    font-size: 16px;
  }
  
  /* 优化按钮触摸区域 */
 .upload-btn{
   min-height: 44px; /* 确保触摸区域足够大 */
  }
  
  /* 优化文件上传区域 */
  .new-file-upload-area {
    min-height: 140px;
  }
  
  .upload-area-center {
    min-height: 160px;
  }
  
  /* 优化滚动体验 */
  .form-content {
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth;
  }
  
  /* 优化导航点击区域 */
  .custom-nav-item {
    min-height: 44px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}

/* 横屏时的特殊优化 */
@media screen and (orientation: landscape) and (max-height: 768px) {
  .pc-page-bg {
    padding: 10px 20px;
  }
  
  .page-title {
    margin-bottom: 15px;
  }
  
  .form-content {
    max-height: 65vh;
    padding: 10px 15px;
  }
  
  .section-title {
    margin-bottom: 10px;
    padding-bottom: 8px;
  }
  
  .form-section {
    margin-bottom: 20px;
  }
  
  .form-grid {
    gap: 10px 15px;
  }
  
  .new-media-section {
    gap: 15px;
  }
  
  .new-upload-card {
    min-height: 180px;
  }
  
}

/* 超窄屏适配 (小于768px) */
@media screen and (max-width: 767px) {
  .main-content {
    padding: 15px 20px;
  }
  
  .main-container {
    display: block;
    padding-right: 0;
  }
  
  .left-nav {
    display: none;
  }
  
  .form-content {
    padding: 15px;
    max-height: none;
    width: 100%;
  }
  
  .section-title {
    font-size: 18px;
    margin-bottom: 12px;
  }
  
  /* 控制表单标签字体大小 */
  .form-label {
    font-size: 13px !important;
    line-height: 1.4;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .form-item,
  .form-item.one-sixth,
  .form-item.half-width,
  .form-item.full-width {
    grid-column: span 1;
  }
  
  /* 基本信息部分在超窄屏时的特殊布局 */
  #section-basic .form-grid {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  #section-basic .form-item,
  #section-basic .form-item.one-sixth,
  #section-basic .form-item[style*="grid-column: span 2"] {
    grid-column: span 1;
  }
  
  /* 确保其他表单项在头像下方 */
  #section-basic .form-item:not(.avatar-item) {
    order: 1;
  }
  
  #section-basic .avatar-item {
    grid-column: span 1;
    grid-row: 1;
    align-items: flex-start;
    order: -1;
  }
  
  #section-basic .avatar-upload {
    align-items: flex-start;
  }
  
  #section-basic .avatar-container {
    width: 80px;
    height: 80px;
  }
  
  #section-basic .upload-btn {
    width: 80px;
    height: 32px;
    font-size: 14px;
  }
  
  .new-media-section {
    flex-direction: column;
    gap: 15px;
  }
  
  .new-upload-card {
    min-width: auto;
    min-height: 200px;
  }
  
}
</style>
